package com.rq.base.ui.common;


import android.app.AlertDialog;
import android.content.Context;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.util.SparseArray;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.TextView;

import com.rq.base.R;
import com.rq.base.util.LOG;

import androidx.annotation.NonNull;


public class CommonDialog extends AlertDialog implements View.OnClickListener {


    public static class Builder {
        Context context;
        int layoutId = R.layout.dialog_common;
        SparseArray<CharSequence> showStr = new SparseArray<>();
        SparseArray<CharSequence> btnStr = new SparseArray<>();
        SparseArray<OnDialogInterface> clickId = new SparseArray<>();
        OnDismissListener onDismissListener;

        int specialId;
        Object[] specialObj;
        ViewDeal mViewDeal;

        public Builder(Context context) {
            this.context = context;
        }

        public Builder setContentView(int layout) {
            this.layoutId = layout;
            return this;
        }

        public Builder setObject(int layoutId, ViewDeal viewDeal, Object... bigSS) {
            this.specialId = layoutId;
            this.specialObj = bigSS;
            this.mViewDeal = viewDeal;
            return this;
        }

        public Builder addString(int layoutId, CharSequence show) {
            this.showStr.put(layoutId, show);
            return this;
        }


        public Builder addButton(int layoutId, String btnStr,
                                 OnDialogInterface clickListener) {
            this.btnStr.put(layoutId, btnStr);
            this.clickId.put(layoutId, clickListener);
            return this;
        }

        public Builder addOnClick(OnDialogInterface clickListener, int... layoutId) {
            if (layoutId != null && layoutId.length > 0) {
                for (int i : layoutId) {
                    this.clickId.put(i, clickListener);
                }
            }
            return this;
        }

        public CommonDialog create() {
            return new CommonDialog(this);
        }

        public Builder addDismissListener(OnDismissListener onDismissListener) {
            this.onDismissListener = onDismissListener;
            return this;
        }
    }

    public void hideIcon() {
    }

    public interface ViewDeal {

        void showView(View viewPan, View viewById, Object[] specialObj);
    }

    public interface OnDialogInterface {

        void onClick(CommonDialog commonDialog, int vId);
    }


    OnConfirmClickListener mOnConfirmClickListener;
    Object clickData;
    private TextView cancel;
    private TextView confirm;
    private View vLine;

    public CommonDialog(@NonNull Builder builder) {
        super(builder.context);
        initBuilder(builder);
    }

    public CommonDialog(@NonNull Context activity) {
        super(activity);
        init(activity, null);
    }

    public CommonDialog(@NonNull Context activity, String res) {
        super(activity);
        init(activity, res);
    }


    public CommonDialog(@NonNull Context activity, String res, int layout) {
        super(activity);
        init(activity, res, layout);
        this.isAutoSize = true;
        LOG.e("CommonDialog", "CommonDialog.42:");
    }

    View parent;

    public String getInput(int viewId) {
        try {
            return ((EditText) findViewById(viewId)).getText().toString().trim();
        } catch (Exception e) {
            try {
                return ((TextView) findViewById(viewId)).getText().toString().trim();
            } catch (Exception e1) {
                return "";
            }
        }
    }

    private CommonDialog init(final Context activity, String msg) {
        return init(activity, msg, R.layout.dialog_common);
    }

    private CommonDialog initBuilder(final Builder builder) {
        LOG.e("CommonDialog", "init.48:");
        parent = LayoutInflater.from(builder.context).inflate(builder.layoutId, null);
        for (int i = 0; i < builder.showStr.size(); i++) {
            TextView itemView = parent.findViewById(builder.showStr.keyAt(i));
            if (itemView != null) {
                itemView.setText(builder.showStr.get(builder.showStr.keyAt(i)));
            }
        }
        for (int i = 0; i < builder.btnStr.size(); i++) {
            try {
                TextView itemView = parent.findViewById(builder.btnStr.keyAt(i));
                if (itemView != null) {
                    if (TextUtils.isEmpty(builder.btnStr.get(builder.btnStr.keyAt(i)))) {
                        itemView.setVisibility(View.GONE);
                    } else {
                        itemView.setText(builder.btnStr.get(builder.btnStr.keyAt(i)));
                    }
                }
            } catch (Exception e) {
                Log.e("CommonDialog", "暂时只支持TextView内容填充");
            }
        }
        if (builder.mViewDeal != null && parent.findViewById(builder.specialId) != null) {
            builder.mViewDeal
                    .showView(parent, parent.findViewById(builder.specialId), builder.specialObj);
        }
        for (int i = 0; i < builder.clickId.size(); i++) {
            View itemView = parent.findViewById(builder.clickId.keyAt(i));
            if (itemView != null) {
                final int finalI = i;
                itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        builder.clickId.get(builder.clickId.keyAt(finalI))
                                .onClick(CommonDialog.this, v.getId());
                    }
                });
            }
        }
        if (builder.onDismissListener != null) {
            setOnDismissListener(builder.onDismissListener);
        }
        initView(parent);
        return this;
    }

    private CommonDialog init(final Context activity, String msg, int layout) {
        parent = LayoutInflater.from(activity).inflate(layout, null);
        initView(parent);
        this.cancel = parent.findViewById(R.id.dialog_cancel);
        this.confirm = parent.findViewById(R.id.dialog_confirm);
        this.vLine = parent.findViewById(R.id.dialog_line);
        if (this.cancel != null) cancel.setOnClickListener(this);

        confirm.setOnClickListener(this);
        TextView title = parent.findViewById(R.id.dialog_content);
        if (title != null && !TextUtils.isEmpty(msg)) {
            if (msg.contains("\\n")) {
                title.setGravity(Gravity.LEFT | Gravity.CENTER_VERTICAL);
            }
            LOG.e("CommonDialog", "init.203:" + msg);
            String newMsg = msg.replaceAll("\\\\", "\\").replaceAll("\\n", "<br>");
            LOG.e("CommonDialog", "init.205:" + newMsg);
            //      title.setText(Html.fromHtml(newMsg, null, new MxgsaTagHandler(activity)));
            title.setText(Html.fromHtml(newMsg));
        }
        LOG.e("CommonDialog", "init.215:" + cancelAble);
        return this;
    }

    protected void initView(View view) {
        this.cancel = view.findViewById(R.id.dialog_cancel);
        this.confirm = view.findViewById(R.id.dialog_confirm);
        this.vLine = view.findViewById(R.id.dialog_line);
        LOG.e("CommonDialog", "initView.220:" + cancelAble);
        if (this.cancel != null) this.cancel.setVisibility(cancelAble ? View.VISIBLE : View.GONE);
        if (vLine != null) this.vLine.setVisibility(cancelAble ? View.VISIBLE : View.GONE);
    }

    @Override
    public <T extends View> T findViewById(int id) {
        return parent.findViewById(id);
    }

    public void setBtnShow(boolean cancel, boolean confirm) {
        if (this.cancel != null) this.cancel.setVisibility(cancel ? View.VISIBLE : View.GONE);
        if (this.confirm != null) this.confirm.setVisibility(confirm ? View.VISIBLE : View.GONE);
        if (vLine != null) this.vLine.setVisibility(confirm && cancel ? View.VISIBLE : View.GONE);
    }

    public void setClickListener(OnConfirmClickListener listener) {
        this.mOnConfirmClickListener = listener;
    }

    @Override
    public final void show() {
        this.show(null);
    }

    boolean isAutoSize = false;
    boolean cancelAble = true;
    float widthRate = 0, heightRate = 0;

    /**
     * 相对于屏幕短边宽度的比例
     *
     * @param widthRate
     * @param heightRate
     */
    public void setSizeRate(float widthRate, float heightRate) {
        this.widthRate = widthRate;
        this.heightRate = heightRate;
    }


    public void show(Object obj) {
        this.clickData = obj;
        try {
            super.show();
        } catch (Exception e) {
            e.printStackTrace();
        }
        setContentView(parent);
        initView(parent);
        Window dialogWindow = getWindow();
        dialogWindow.clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
        dialogWindow.setGravity(Gravity.CENTER);
        dialogWindow.getDecorView().setPadding(0, 0, 0, 0);
        dialogWindow.setBackgroundDrawableResource(android.R.color.transparent);
        int width = getWindow().getContext().getResources().getDisplayMetrics().widthPixels;
        int height = getWindow().getContext().getResources().getDisplayMetrics().heightPixels;
        int vWidth = parent.getPaddingLeft();
        LOG.e("CommonDialog", vWidth + ".width:" + width + "  height:" + height);
        //        if (this.isAutoSize) {
        //            lp.width = width;
        //            lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        int minSize = Math.min(width, height);
        if (widthRate > 0 || heightRate > 0) {
            int w = ViewGroup.LayoutParams.WRAP_CONTENT;
            int h = ViewGroup.LayoutParams.WRAP_CONTENT;
            if (widthRate > 0) {
                w = (int) (widthRate * minSize);
            }
            if (heightRate > 0) {
                h = (int) (heightRate * minSize);
            }
            dialogWindow.setLayout(w, h);
        } else {
            getWindow().setLayout(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        }
        //        } else {
        //            lp.width = (int) (width * 0.6F);
        //            lp.height = (int) (width * 0.4F);
        //        }
        //        dialogWindow.setAttributes(lp);
    }

    @Override
    public void setCancelable(boolean flag) {
        super.setCancelable(flag);
        cancelAble = flag;
    }

    @Override
    public void onClick(View v) {
        if (mOnConfirmClickListener != null) {
            mOnConfirmClickListener.onClickConfirm(v.getId() == R.id.dialog_confirm, clickData);
        }
        if (v.getId() == R.id.dialog_confirm || this.cancelAble) {
            dismiss();
        }
    }

    public interface OnConfirmClickListener<T> {
        // isConfirm 取消按钮
        void onClickConfirm(boolean isConfirm, T data);
    }
}